<template>
    <ContentField>
        <div class="row justify-content-md-center" v-if="!$store.state.user.pulling_info">
            <div class="col-3">
                <form @submit.prevent="login">
                    <div class="mb-3">
                        <label for="username" class="form-label">用户名</label>
                        <input v-model="username" type="text" class="form-control" id="username" placeholder="请输入用户名">
                    </div>

                    <div class="mb-3">
                    <label for="password" class="form-label">密码</label><!--  //v-module:将input中的password与下方setup函数中的值对应起来 -->
                    <input v-model="password" type="password" class="form-control" id="password" placeholder="请输入密码">
                    </div>
                    <div class="error_message">{{error_message}}</div>
                    <button type="submit" class="btn btn-primary">提交</button>
                </form>
            </div>
        </div>
    </ContentField>
</template>

<script scope>
import ContentField from '@/components/ContentField.vue';
import { useStore } from 'vuex';
import { ref } from 'vue';
import router from '@/router';
/* import store from '@/store/index'; */

export default {
    components: {
        ContentField
    },

    setup() {
        const store = useStore();
        let username = ref('');
        let password = ref('');
        let error_message = ref('');

        const jwt_token = localStorage.getItem("jwt_token"); // 登入之后取得token，在未到期之前可以自动登入
        if (jwt_token) {
            store.commit("updateToken", jwt_token); // 调用mutations中的updateToken函数
            store.dispatch("getinfo", { // 从云端获取信息, 即令牌还未过期的话
                success() {
                    router.push({name : "home"}); // 若是成功的话跳转到首页
                    store.commit("updatePullingInfo", false);
                },

                error() {
                    store.commit("updatePullingInfo", false); // 若是令牌过期将登入业面展示出来
                }

            })
        } else {
           store.commit("updatePullingInfo", false);// 若是本地没有token的话将登入业面展示出来
        }

        const login = () => { //若点击触发这个函数
            error_message.value = "";
            store.dispatch("login", { // dispatch调用action 函数
                username: username.value,
                password: password.value,

                success() {
                    store.dispatch("getinfo", {
                        success() {
                            router.push({name:"home"}); // 若登入成功自动跳转到home界面
                            console.log(store.state.user);
                        }
                    })
                },

                error() {
                    error_message.value = "用户名或密码错误";
                }
            })
        }

        return {
            username,
            password,
            error_message,
            login,
        }
    }
}
</script>

<style>
button{
    width: 100%;
}

.error_message{
    color: red;
}
</style>